<?php
namespace Home\Model;

use Think\Model;

class AvatarModel extends Model
{
    public function addAvatar($data)
    {
        return $this->add($data);
    }

    public function deleteAvatarByUserId($user_id){
        $this->where("user_id='$user_id'")->delete();
        //还需要图片文件操作 T T
    }

    public function updateAvatarById($id, $data)
    {
        $this->where("id='$id'")->save($data);
    }


    public function uploadAvatar(){

    }

    public function updateAvatarByUserId($id)
    {
        $dir = 'Public/images/';
        $old_avatar = $this->getAvatarById($id);
        $delete_avatar = $dir.$old_avatar[0]['name'];
//        dump($old_avatar);die();
        $config = array(//设置上传类参数
            'maxSize'    =>    3145728,
            'rootPath'   =>    './Public/',
            'savePath'   => 'images/',
            'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
        );
        $upload = new \Think\Upload($config);// 实例化上传类
        $photo_name=md5(uniqid(microtime(true),true)).'.'.end(explode('.',$_FILES['file']['name']));
        $_FILES['file']['name']=$photo_name;//改头像名
        $info = $upload->upload($_FILES);//上传
        if(!$info) return ['status' => 'error', 'info' => $upload->getError()];
        if($old_avatar[0]['name']!='default.jpg'){//判断是是否为default.jpg
            if (file_exists($delete_avatar)) {
                unlink($delete_avatar);
            }
        }
        $target_path='Public/images/'.$photo_name;
        move_uploaded_file($_FILES['file']['tmp_name'],$target_path);
        $data['name']=$photo_name;
        $this->where("user_id='$id'")->save($data);
        return ['status' => 'success', 'info' => '图片更新成功'];
    }

    public function getAvatarById($id)
    {
        return $this->where("user_id='$id'")->select();
    }

    public function getAvatarByUserId($user_id)
    {
        return $this->where("user_id='$user_id'")->select();
    }

}